<template>
	<jk-card>
		<div v-loading="contentLoading" class="schedule-container" :body-style="{ paddingTop: '10px' }">
			<el-row class="date-nav">
				<el-col :span="8" class="flex-start-center">
					<el-dropdown class="item-gap" @command="onSelectWorkshop">
						<el-button :size="buttonSize" icon="">
							<span class="el-icon-house"></span>
							{{ workshopName ? workshopName : '暂无区域' }}
							<i class="el-icon-arrow-down el-icon--right"></i></el-button>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item
								v-for="item in workshopList"
								:key="item.id"
								:command="item.id"
								icon="el-icon-s-home"
							>{{ item.name }}</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
					<el-button-group class="item-gap">
						<el-button :size="buttonSize" icon="el-icon-top-left" class="current-month" @click="onCurrentMonthButton">回到当月</el-button>
					</el-button-group>
					<div class="legend-bar">
						<div
							v-for="item in legendData"
							:key="item.shiftTypeId"
							class="legend-item"
						>
							<div class="legend-icon" :style="{background: item.color}"></div>
							<div>{{ item.shiftTypeName }}</div>
						</div>
					</div>
				</el-col>
				<el-col :span="8" class="flex-center">
					<el-button size="" icon="el-icon-d-arrow-left" @click="onPreMonthButton"></el-button>
					<div class="month-title" @click="onRefreshButton">
						<div class="el-icon-date"></div>
						<span>{{ currentMonth }}</span>
					</div>
					<el-button size="" icon="el-icon-d-arrow-right" @click="onNextMonthButton"></el-button>
				</el-col>
				<el-col :span="8" class="flex-end-center">
					<auto-schedule-btn
						class="item-gap"
						:workshop-id="workshopId"
						:size="buttonSize"
						@on-confirm="onRefreshButton"
					></auto-schedule-btn>
					<batch-delete-group-btn
						:size="buttonSize"
						:workshop-id="workshopId"
						@on-confirm="onRefreshButton"
					></batch-delete-group-btn>
				</el-col>
			</el-row>
			<div class="week-header-container">
				<span v-for="(item, index) in dateHeader" :key="index" class="week-header">{{ item }}</span>
			</div>
			<div class="date-container">
				<div v-for="(allItem, allIndex) in dateList" :key="allIndex" class="date-body">
					<!--日期-->
					<div v-for="(item) in allItem" :key="item.date" class="date-body-item" :style="isDateItemBgColor(item)">
						<!--						<el-checkbox v-if="!item.scheduleShiftList" :value="item.date" :label="item.date" class="check-box-position">{{ item.day ? '' : '' }}</el-checkbox>-->
						<div v-if="item.isCurrentMonth" :class="item.scheduleShiftList ? 'date-item-num date-item-has date-item-num-hover' : 'date-item-num'" :style="{opacity: !item.isCurrentMonth ? '0.4' : ''}">{{ item.day }}</div>
						<div v-else :class="item.scheduleShiftList ? 'date-item-num date-item-num-hover' : 'date-item-num'" :style="{opacity: !item.isCurrentMonth ? '0.2' : ''}">{{ item.day }}</div>
						<div v-if="item.scheduleShiftList && item.isCurrentMonth" class="date-item-schedule">
							<a class="calendar-shift-type" @click="onClickSetSchedule(item)">{{ item.shiftTypeName }}</a>
							<!--班制-->
							<div v-for="(shiftItem, shiftIndex) in item.scheduleShiftList" :key="shiftIndex" class="group-bar">
								<i class="schedule-circle-icon" />
								<span class="shift-item-name">{{ shiftItem.shiftName }}:</span>
								<!--班组-->
								<div v-for="(groupItem, groupIndex) in shiftItem.scheduleGroupList" :key="groupIndex" class="group-bar-item">
									<a class="group-item" @click="onClickGroup(item, shiftItem, groupItem)">{{ groupItem.groupName }}</a>
								</div>
							</div>
						</div>
						<div v-else>
							<span v-if="item.isCurrentMonth" class="date-item-schedule-null" @click="onClickSetSchedule(item)">排班</span>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!--排班-->
		<save-schedule-dialog
			:dialog-state="saveScheduleDialogState"
			:data-item="dataItem"
			@on-visible-change="onVisibleChangeSaveScheduleDialog"
			@on-confirm="onConfirmButtonSaveScheduleDialog"
		/>
		<!--设置班组人员-->
		<set-group-emp-dialog
			:check-data="checkData"
			:dialog-state="setGroupEmpDialogState"
			@on-visible-change="(e) => setGroupEmpDialogState = e"
		></set-group-emp-dialog>
	</jk-card>
</template>
<script>
    import { formatDate } from '../../../utils/jk/jk-tool';
    import saveScheduleDialog from './save-schedule-dialog';
    import {
        workforcemanagementScheduleList
    } from '../../../api/schedule/scheduling';
    import handlerCache from '../../../mixins/handler-cache';
    import setGroupEmpDialog from './set-group-emp-dialog';
    import saveDialog from '../empMachine/save-dialog';
    import autoScheduleBtn from './compomens/auto-schedule-btn';
    import batchDeleteGroupBtn from './compomens/batch-delete-group-btn';
    export default {
        name: 'Scheduling',
        components: { batchDeleteGroupBtn, autoScheduleBtn, setGroupEmpDialog, saveScheduleDialog, saveDialog },
        mixins: [handlerCache],
        data() {
            return {
                setGroupEmpDialogState: false,
                legendData: [],
                buttonSize: 'mini',
                dateData: [],
                saveScheduleDialogState: false,
                workshopList: [],
                workshopId: null,
                workshopName: '',
                contentLoading: false,
                dateHeader: ['日', '一', '二', '三', '四', '五', '六'],
                dateList: [],
                rawData: [],
                currentMonth: '',
                currentDate: '',
                dataItem: {
                    workshopId: null,
                    workshopName: '',
                    date: []
                },
                toMounted: false,
                checkData: {}
            };
        },
        computed: {
            isDateItemBgColor() {
                return (item) => {
                    if (item.isCurrentMonth) {
                        return {
                            borderColor: item.scheduleShiftList ? '#fff' : '',
                            background: formatDate(Date.parse(item.date)) === formatDate(Date.parse(this.currentDate)) ? '#5cadff' : item.bgColor
                        };
                    }
                };
            }
        },
        methods: {
            clearCacheMethod() {
                this.getInitData();
            },
            getInitData() {
                this.contentLoading = true;
                this.currentMonth = this.getCurrentMonth();
                this.getMonthDays(this.currentMonth);
                this.contentLoading = false;
            },
            onSelectWorkshop(e) {
                if (e) {
                    this.workshopId = e;
                    this.workshopName = this.workshopList.find(x => x.id === e).name;
                }
                this.getMonthDays(this.currentMonth);
            },
            onClickGroup(item, shiftItem, e) {
                this.checkData = {
                    ...item,
                    shiftItem: shiftItem,
                    scheduleGroupId: e.id,
                    scheduleGroupName: e.groupName
                };
                this.setGroupEmpDialogState = true;
            },
            onRefreshButton() {
                this.getScheduleListRequest(this.dateData[0].date, this.dateData[this.dateData.length - 1].date);
            },
            getScheduleListRequest(dateFrom, dateTo) {
                this.contentLoading = true;
                return workforcemanagementScheduleList({
                    workshopId: this.workshopId,
                    belongDateFrom: dateFrom,
                    belongDateTo: dateTo
                }).then(res => {
                    this.contentLoading = false;
                    if (res.data.status === 200) {
                        this.setLegend(res.data.res);
                        this.rawData.forEach(item => {
                            res.data.res.forEach(resItem => {
                                if (resItem.belongDate === item.date) {
                                    item.scheduleShiftList = JSON.parse(JSON.stringify(resItem.scheduleShiftList));
                                    item.workshopId = this.workshopId;
                                    item.isCompute = resItem.isCompute;
                                    item.isOnDuty = resItem.isOnDuty;
                                    item.shiftTypeId = resItem.shiftTypeId;
                                    item.shiftTypeName = resItem.shiftTypeName;
                                    item.bgColor = '#f6f7f6';
                                    item.scheduleId = resItem.id || null;
                                    this.legendData.forEach(x => {
                                        if (resItem.shiftTypeId === x.shiftTypeId) {
                                            item.bgColor = x.color;
                                        }
                                    });
                                }
                            });
                        });
                        // 分组（7天为一组）
                        const arr = [];
                        for (let i = 0, len = this.rawData.length; i < len; i += 7) {
                            arr.push(this.rawData.slice(i, i + 7));
                        }
                        this.dateList = JSON.parse(JSON.stringify(arr));
                    }
                });
            },
            setLegend(resData) {
                const colors = ['#D2E3FC', '#FEE6DC', '#d8c1f7', '#DCEEE2'];
                const obj = {};
                this.legendData = resData.reduce((item, next) => {
                    if (!obj[next.shiftTypeId]) {
                        item.push(next);
                        obj[next.shiftTypeId] = true;
                    }
                    return item;
                }, []);

                this.legendData = this.legendData.map((x, idx) => {
                    return {
                        shiftTypeId: x.shiftTypeId,
                        shiftTypeName: x.shiftTypeName,
                        color: colors[idx]
                    };
                });
            },
            onConfirmButtonSaveScheduleDialog() {
                this.saveScheduleDialogState = false;
                this.getMonthDays(this.currentMonth);
            },
            onClickSetSchedule(a) {
                const e = JSON.parse(JSON.stringify(a));
                if (e.isCompute) {
                    return false;
                }
                this.saveScheduleDialogState = true;
                this.dataItem = {
                    scheduleId: e.scheduleId,
                    workshopId: this.workshopId,
                    workshopName: this.workshopName,
                    date: e.date,
                    scheduleShiftList: e.scheduleShiftList,
                    shiftTypeId: e.shiftTypeId ? e.shiftTypeId : null
                };
            },
            onVisibleChangeSaveScheduleDialog(e) {
                this.saveScheduleDialogState = e;
                // this.getMonthDays(this.currentMonth);
            },
            // 获取当前月份
            getCurrentMonth() {
                const d = new Date(Date.now());
                const month = d.getMonth() + 1;
                const day = d.getDate();
                this.currentDate = `${d.getFullYear()}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
                return `${d.getFullYear()}-${month < 10 ? '0' + month : month}`;
            },
            onPreMonthButton() {
                this.currentMonth = this.getPreMonth(this.currentMonth);
                this.getMonthDays(this.currentMonth);
            },
            onCurrentMonthButton() {
                this.currentMonth = this.getCurrentMonth();
                this.getMonthDays(this.currentMonth);
            },
            onNextMonthButton() {
                this.currentMonth = this.getNextMonth(this.currentMonth);
                this.getMonthDays(this.currentMonth);
            },
            // 上一个月
            getPreMonth(date) {
                const d = new Date(date);
                let year = d.getFullYear();
                let month = d.getMonth();
                if (month === 0) {
                    year = year - 1;
                    month = 12;
                }
                return `${year}-${month < 10 ? '0' + month : month}`;
            },
            // 下一个月
            getNextMonth(date) {
                const d = new Date(date);
                let year = d.getFullYear();
                let month = d.getMonth() + 1;
                month = month + 1;
                if (month === 13) {
                    year = year + 1;
                    month = 1;
                }
                return `${year}-${month < 10 ? '0' + month : month}`;
            },
            // 获取某个月的天数
            getMonthDays(date) {
                const d = new Date(date);
                const year = d.getFullYear();
                const month = d.getMonth() + 1;
                const days = new Date(year, month, 0).getDate();
                this.rawData = [];
                // 所选月份的所有天数
                for (let i = 1; i <= days; i++) {
                    this.rawData.push({
                        date: `${date}-${i < 10 ? '0' + i : i}`,
                        timeStamp: Date.parse(`${date}-${i < 10 ? '0' + i : i}`),
                        day: i,
                        isCurrentMonth: true
                    });
                }
                // 获取所选月份的1号是星期几
                const firstDayToWeek = new Date(`${date}-1`).getDay();
                // 获取所选月份的最后一天是星期几
                const lastDayToWeek = 7 - (new Date(`${date}-${days}`).getDay() + 1);

                // 在前面填充上月的日期
                for (let i = 1; i <= firstDayToWeek; i++) {
                    this.rawData.unshift({
                        date: formatDate(Date.parse(`${date}-1`) - (i * 24 * 60 * 60 * 1000)),
                        timeStamp: Date.parse(`${date}-1`) - (i * 24 * 60 * 60 * 1000),
                        day: new Date(Date.parse(`${date}-1`) - (i * 24 * 60 * 60 * 1000)).getDate(),
                        isCurrentMonth: false
                    });
                }
                // 在后面填充下月的日期
                for (let i = 1; i <= lastDayToWeek; i++) {
                    this.rawData.push({
                        date: formatDate(Date.parse(`${date}-${days}`) + (i * 24 * 60 * 60 * 1000)),
                        timeStamp: Date.parse(`${date}-${days}`) + (i * 24 * 60 * 60 * 1000),
                        day: new Date(Date.parse(`${date}-${days}`) + (i * 24 * 60 * 60 * 1000)).getDate(),
                        isCurrentMonth: false
                    });
                }
                this.dateData = JSON.parse(JSON.stringify(this.rawData));
                this.getScheduleListRequest(this.rawData[0].date, this.rawData[this.rawData.length - 1].date);
            }
        },
        mounted() {
            this.workshopId = this.$store.state.user.userWorkshop.defaultWorkshopId;
            this.workshopName = this.$store.state.user.userWorkshop.defaultWorkshopName;
            this.workshopList = this.$store.state.user.userWorkshop.workshopList;
            this.toMounted = true;
            this.getInitData();
        }
    };
</script>
<style scoped lang="scss">
    @import "./schedule.scss";
</style>
